//
//  SEGMyProfileViewController.m
//  ExcellentHome
//
//  Created by 刘山 on 16/11/22.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGMyProfileViewController.h"
#import "SEGAdressListViewController.h"
#import "SEGEditDetailViewController.h"
#import "SEGMyLevelViewController.h"

#import "SEGMyProfileHeaderViewCell.h"

#if __has_include(<commonThirds/SEGImagePickerManager.h>)
#import <commonThirds/SEGImagePickerManager.h>
#else
#import "SEGImagePickerManager.h"
#endif

#import "SEGMyProfileViewModel.h"

static NSString* SEGMyProfileHeaderViewCellIndentifier = @"_SEGMyProfileHeaderViewCellIndentifier";

@interface SEGMyProfileViewController () <UITableViewDataSource, UITableViewDelegate, EditDetailViewControllerDelegate, UIActionSheetDelegate, UINavigationControllerDelegate, SEGImagePickerManagerDelegate>
 
@property (nonatomic, strong) UITableView *tableView;
/** 相机, 相册 */
@property (nonatomic, strong) SEGImagePickerManager *imagePicker;

/// viewModel
@property (nonatomic, strong) SEGMyProfileViewModel *viewModel;

@end

@implementation SEGMyProfileViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    @weakify(self);
    [[self.viewModel.profileCommand execute:@""] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.tableView reloadData];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人资料";
    [self setupUI];
    
    // 初始化数据
    [self.viewModel doLogic_myprofile];
    [self.tableView reloadData];
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = kColor_bg;
    [self.tableView registerClass:[SEGMyProfileHeaderViewCell class] forCellReuseIdentifier:SEGMyProfileHeaderViewCellIndentifier];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}
// 更新UI
- (void)updateUI {
    [self.viewModel doLogic_myprofile];
    [self.tableView reloadData];
    // 通知个人主页更新
    [[NSNotificationCenter defaultCenter] postNotificationName:SEGEditUserInfoFinishedNotification object:nil];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.seg_segmyprofilelogicmodel.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGMyProfileHeaderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SEGMyProfileHeaderViewCellIndentifier];
    if (cell == nil) {
        cell = [[SEGMyProfileHeaderViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SEGMyProfileHeaderViewCellIndentifier];
    }
    cell.ContentLabel.hidden = NO;
    cell.picImageView1.hidden = NO;
    cell.tag = 666;
    if (indexPath.row < self.viewModel.seg_segmyprofilelogicmodel.count) {
        SEGMyProfileLogicModel *data = self.viewModel.seg_segmyprofilelogicmodel[indexPath.row];
        if ([data.key isEqualToString:@"1"]) { //1:修改头像
            cell.cellType = MyProfileHeaderType_HEAD;
            UIImage *image = [UIImage imageWithData:self.viewModel.imageData];
            if (!image) {
                image = [UIImage imageWithContentsOfFile:SEGPicName(@"headimg160")];
            }
            [cell.picImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kClientImageRootURL, data.desc]] placeholderImage:image];
            
            cell.ContentLabel.text = data.name;
            cell.titleLabel.text = data.name;
            cell.ContentLabel.hidden = YES;
        } else {
            cell.ContentLabel.textColor = kColor_1;
            cell.picImageView1.hidden = NO;
            if([data.key isEqualToString:@"4"]){  //4:手机号码
                cell.tag = 999; //记录没有展开箭头的布局
                //手机号置灰
                cell.picImageView1.hidden = YES;
                cell.ContentLabel.textColor = kColor_3;
            }
            
            if ([data.key isEqualToString:@"6"]) { //6：等级
                cell.tag = 888;
                //重新布局等级
                NSString *levelStr = [SEGProfileManager sharedManager].profile.level;
                NSString *imageL = [SEGProfileManager sharedManager].profile.levelUrl;
                [cell.levelimageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,imageL]] placeholderImage:nil];
                
                //如果没有等级图片，调整布局
                if (imageL.length == 0) {
                    cell.tag = 777;
                }
                cell.cellType = MyProfileHeaderType_NORMAL;
                cell.ContentLabel.text = levelStr;
                cell.titleLabel.text = data.name;
                
            } else {
                //其余正常展示Cell的布局
                cell.cellType = MyProfileHeaderType_NORMAL;
                cell.ContentLabel.text = data.desc;
                cell.titleLabel.text = data.name;
                
                if ([data.key isEqualToString:@"5"]) { //个人描述
                    cell.ContentLabel.text = data.desc && [data.desc length] > 0 ? data.desc : @"还未添加任何个人描述";
                }
                
                if ([data.key isEqualToString:@"4"]) {
                    if (!data.desc || data.desc.length == 0) {
                        cell.ContentLabel.text = @"";
                    }else{
                        NSString *phoneString;
                        if (data.desc.length >= 7) {
                            phoneString = [data.desc stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
                        }else {
                            phoneString = data.desc;
                        }
                        cell.ContentLabel.text = phoneString;
                    }
                }
                
                if ([data.key isEqualToString:@"7"]) {
                    if ([data.desc isEqualToString:@"1"]) {
                        cell.ContentLabel.text = @"女";
                    }else{
                        cell.ContentLabel.text = @"男";
                    }
                }
                
            }
        }
        
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0)
    {
        [cell layoutIfNeeded];
    }
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView*)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath*)indexPath {
    return 44;
}
- (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
    if (indexPath.row < self.viewModel.seg_segmyprofilelogicmodel.count) {
        SEGMyProfileLogicModel *data = self.viewModel.seg_segmyprofilelogicmodel[indexPath.row];
        switch ([data.key integerValue]) {
            case 1: { //修改头像
                UIActionSheet *actionSheetView = [[UIActionSheet alloc] initWithTitle:nil
                                                                             delegate:self
                                                                    cancelButtonTitle:@"取消"
                                                               destructiveButtonTitle:nil
                                                                    otherButtonTitles:@"拍照", @"相册", nil];
                [actionSheetView showInView:self.view];
            } break;

        case 2: { //昵称
            SEGEditDetailViewController* myAddressList = [[SEGEditDetailViewController alloc] init];
            myAddressList.title = @"昵称";
            myAddressList.placeholder = @"请输入新的昵称";
            myAddressList.contentText = data.desc;
            myAddressList.delegate = self;
            myAddressList.isNotEmpty = YES;
            myAddressList.userInfo = @{
                @"name" : @"nickName"
            };
            myAddressList.showType = EditDetailShowType_UITextField;
            myAddressList.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:myAddressList animated:YES];
        } break;

        case 3: { //配送地址
            SEGAdressListViewController* myAddressList = [[SEGAdressListViewController alloc] init];
            myAddressList.showType = AdressListViewControllerType_My;
            myAddressList.addressSelected = @"183";
            myAddressList.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:myAddressList animated:YES];
        } break;

        case 4: { //手机号码
            [SEGAlertView showTmepMessageWithMessage:@"手机号不能编辑"];
        } break;

        case 5: { //个人描述
            SEGEditDetailViewController* myAddressList = [[SEGEditDetailViewController alloc] init];
            myAddressList.title = @"个人描述";
            myAddressList.placeholder = @"请输入新的个人描述";
            myAddressList.contentText = data.desc;
            myAddressList.delegate = self;
            myAddressList.showType = EditDetailShowType_UITextView;
            myAddressList.hidesBottomBarWhenPushed = YES;
            myAddressList.userInfo = @{
                @"name" : @"desc"
            };
            [self.navigationController pushViewController:myAddressList animated:YES];
        } break;
        case 6: { //等级
            NSDictionary *params = @{@"linkURL" : kIntegarlLvcondition};
            UIViewController *myLevel = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:params];
            myLevel.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:myLevel animated:YES];
            
            return;
            } break;
            
        case 7: {   //性别
            SEGEditDetailViewController* myMaleList = [[SEGEditDetailViewController alloc] init];
            myMaleList.title = @"设置性别";
            myMaleList.recordSex = [SEGProfileManager sharedManager].profile.sex;
            myMaleList.editType = EditJobAndMaleType_Male;  //CELL 样式为性别
            myMaleList.showType = EditDetailShowType_UITableView;   //展示table布局
            myMaleList.userInfo = @{@"name" : @"sex"};
            myMaleList.delegate = self;
            myMaleList.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:myMaleList animated:YES];
            
            }break;
        case 8: {   //职业
            SEGEditDetailViewController* myMaleList = [[SEGEditDetailViewController alloc] init];
            myMaleList.title = @"选择职业";
            myMaleList.recordProfessionId = [SEGProfileManager sharedManager].profile.job;
            myMaleList.editType = EditJobAndMaleType_Job;   //CELL 样式为职业
            myMaleList.showType = EditDetailShowType_UITableView;   //展示table布局
            myMaleList.delegate = self;
            myMaleList.userInfo = @{@"name" : @"job"};
            myMaleList.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:myMaleList animated:YES];
            }
                
        default:
            break;
        }
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        self.imagePicker = [[SEGImagePickerManager alloc] init];
        self.imagePicker.delegate = self;
        self.imagePicker.sourceType = SEGImagePickerManagerSourceTypeCamera;
        self.imagePicker.allowsEditing = YES;
        [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
    } else if (buttonIndex == 1) {
        self.imagePicker = [[SEGImagePickerManager alloc] init];
        self.imagePicker.delegate = self;
        self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
        self.imagePicker.allowsEditing = YES;
        [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
    }
}

#pragma mark - SEGImagePickerManagerDelegate
- (void)seg_imagePickerManager:(SEGImagePickerManager *)manager
        didFinishPickingPhotos:(NSArray<UIImage *> *)photos 
                        assets:(NSArray<PHAsset *> *)assets
         isSelectOriginalPhoto:(BOOL)isSelect {
    @weakify(self);
    UIImage *editedImage = [photos lastObject];
    [[self.viewModel.uploadIconCommand execute:editedImage] subscribeNext:^(NSString *errorMessage) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:errorMessage];
        // 更新UI
        [[NSNotificationCenter defaultCenter] postNotificationName:SEGEditUserInfoFinishedNotification object:nil];
        [self updateUI];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

#pragma mark - EditDetailViewControllerDelegate
- (void)response_DataWithUserInfo:(NSDictionary *)userInfo Params:(NSDictionary *)dict {
    @weakify(self);
    [[self.viewModel.updateInfoCommand execute:RACTuplePack(userInfo, dict)] subscribeNext:^(NSString *errorMessage) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:errorMessage];
        [[NSNotificationCenter defaultCenter] postNotificationName:SEGEditUserInfoFinishedNotification object:nil];
        id lastVC = self.navigationController.viewControllers.lastObject;
        if (lastVC && [lastVC isKindOfClass:[SEGEditDetailViewController class]]) {
            [[(SEGEditDetailViewController*)lastVC navigationController] popViewControllerAnimated:YES];
        }
        [self updateUI];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[SEGMyProfileHeaderViewCell class] forCellReuseIdentifier:SEGMyProfileHeaderViewCellIndentifier];
        if (@available(iOS 11, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _tableView;
}
- (SEGMyProfileViewModel *)viewModel {
    if (!_viewModel) _viewModel = [[SEGMyProfileViewModel alloc] init];
    return _viewModel;
}

@end
